from flask import Flask, jsonify
from handler.user import user
from handler.friend import friend
from db_config import app, db
# socket 版本匹配 vue
# https://github.com/miguelgrinberg/python-socketio/issues/578
# https://stackoverflow.com/questions/65636439/how-to-get-javascript-socket-io-version#
from flask_socketio import SocketIO, send, emit, join_room, leave_room
# 解决跨域问题的模块CORS
from flask_cors import CORS



# 服务器允许 http跨域, socket跨域
CORS(app, supports_credentials = True, cors_allowed_origins="*")

# 添加用户模块 蓝图 user/login   user/register  user/changepwd
# 将蓝图user注册到该应用app中  url_prefix：url前缀
app.register_blueprint(user, url_prefix="/user")

# 添加好友模块
app.register_blueprint(friend, url_prefix="/friend")

# 添加chat模块
# app.register_blueprint(chat, url_prefix="/chat")

# socket实例
socketio = SocketIO(app, cors_allowed_origins='*')
# socketio.init_app(app)


########################################################################################################


######### 在数据库存 userId 和 sessionId后，用socketio.emit("message", {'data': data}, room=sid])

# import urllib.parse

# SocketIO 支持确认回调，确认客户端收到了一条消息：
# def ack():
#     print('message was received!')
# @socketio.on('connect', namespace='/chat')
# def test_connect():
#     emit('my response', {'data': 'Connected'}, callback=ack)


# @socketio.on('message')
# def handle_message(message):
#     message = urllib.parse.unquote(message)
#     print(message)
#     # send 默认发送到 massage 事件
#     send(message, broadcast=True)

# @socketio.on('con', namespace='/chat')
# def test_connect():
#     print('-----connect-----')
#     emit('my response', {'data': 'Connected'})

# @socketio.on('discon', namespace='/chat')
# def test_disconnect():
#     print('-----disconnect-----')
#     print('Client disconnected')

# https://blog.csdn.net/lijiecong/article/details/50781417
# https://blog.csdn.net/q389797999/article/details/82761137
# https://www.cnblogs.com/edwardloveyou/p/10625152.html
# https://www.imooc.com/article/289816

@socketio.on('join')
def on_join(data):
    # id = data["id"]
    # username = data['username']
    room = data['room']
    join_room(room)
    # print(room)
    # send(id + ':' + username + ' has left the room.', room=room)

@socketio.on('leave')
def on_leave(data):
    # id = data["id"]
    # username = data['username']
    room = data['room']
    leave_room(room)
    # print(room)
    # send(id + ':' + username + ' has left the room.', room=room)

@socketio.on('drinktalk')
def on_drinktalk(data):
    msg = (data['username'], data['text'])
    room = data['room']
    emit('drinker', msg, to = room)

########################################################################################################



@app.route('/', methods=['get', 'post'])
def hello():
    data={'state':'Hello world!'}
    # return "Hello world!"
    return jsonify(data)


if __name__=='__main__':
    # 数据库建表
    db.create_all()
    # 应用运行
    # app.run()
    # socketio.run(app)
    # socketio.run(app, host='0.0.0.0', port=5000, debug=True)
    socketio.run(app,debug=True)
    
